﻿using System.Collections.Generic;

namespace Core.RedPoint
{
    public class ChildNode : Core.Component, IAwake, IRedPointNode
    {
        protected readonly Dictionary<string, IRedPointNode> Dict = new();

        public void Awake()
        {
            Dict.Clear();
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            foreach (var item in Dict)
            {
                item.Value.Dispose();
            }
            Dict.Clear();

            base.Dispose();
        }

        public void Add<T>(string[] keys, int index)
            where T : Component, IRedPointNode
        {
            var key = keys[index];
            if (Dict.ContainsKey(key))
            {
                log.err($"ChildNode.Add Error! 存在重复的key，key={key}");
                return;
            }

            if (index == keys.Length - 1)
            {
                var node = G.Factory.Create<T>();
                Dict[key] = node;
            }
            else
            {
                var node = G.Factory.Create<ChildNode>();
                node.Add<T>(keys, index + 1);
                Dict[key] = node;
            }
        }

        public T Get<T>(string[] keys, int index)
            where T : Component, IRedPointNode
        {
            var key = keys[index];
            if (!Dict.ContainsKey(key))
            {
                return default;
            }

            if (index == keys.Length - 1)
            {
                var node = Dict[key];
                return node as T;
            }
            else
            {
                ChildNode node = G.Factory.Create<ChildNode>();
                return node.Get<T>(keys, index + 1);
            }
        }
    }
}
